package com.xzc.lease.web.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzc.lease.model.entity.BrowsingHistory;
import com.xzc.lease.web.app.mapper.BrowsingHistoryMapper;
import com.xzc.lease.web.app.service.BrowsingHistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzc.lease.web.app.vo.history.HistoryItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author 徐生
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {

    @Autowired
    private BrowsingHistoryMapper browsingHistoryMapper;

    /**
     * 获取浏览历史
     *
     * @param page
     * @param userId
     * @return
     */
    public IPage<HistoryItemVo> pageItemByUserId(Page<HistoryItemVo> page, Long userId) {
        return browsingHistoryMapper.pageItemByUserId(page, userId);
    }

    /**
     * 根据userId、roomId保存浏览历史
     *
     * @param userId
     * @param roomId
     */
    @Async //该方法在 根据id获取房间的详细信息 时执行，为了确保不影响其原有的执行速度，设置为异步方法
    public void saveHistoryByUserIdAndRoomId(Long userId, Long roomId) {
        //假设同一个用户多次浏览同一个房间时，此时不需要保存每次的记录。
        //  只在首次访问时保存，后续访问只需要修改访问时间即可。即一个用户一个房间在数据库中只会有一条浏览记录
        LambdaQueryWrapper<BrowsingHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BrowsingHistory::getUserId, userId)
                .eq(BrowsingHistory::getRoomId, roomId);
        BrowsingHistory browsingHistory = browsingHistoryMapper.selectOne(queryWrapper);

        //判断是更新还是添加操作
        if (browsingHistory != null) {
            //更新操作，修改修改时间即可
            browsingHistory.setBrowseTime(new Date());
            browsingHistoryMapper.updateById(browsingHistory);
        } else {
            //添加操作
            browsingHistory = new BrowsingHistory();
            browsingHistory.setUserId(userId);
            browsingHistory.setRoomId(roomId);
            browsingHistory.setBrowseTime(new Date());
            browsingHistoryMapper.insert(browsingHistory);
        }
    }
}